package com.ybwh.springboot2.activiti.service;

import com.google.common.base.Preconditions;
import com.ybwh.springboot2.activiti.WorkflowConstant;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @author fanbeibei
 * @version 1.0.0
 * @date 2022/11/21 17:12
 */
@Slf4j
@Service
public class WorkflowService {

    @Autowired
    private ProcessEngine processEngine;


    /**
     * 开启流程
     *
     * @param processKey  流程定义ID
     * @param businessKey 业务ID
     * @param variables   变量
     * @param userId      当前用户ID
     * @return
     */
    public ProcessInstance startProccess(String processKey, String businessKey, Map<String, Object> variables, String userId) {
        Preconditions.checkArgument(StringUtils.isNotBlank(processKey));
        Preconditions.checkArgument(StringUtils.isNotBlank(businessKey));

        if (null == variables) {
            variables = new HashMap<>();
        }

        variables.put(WorkflowConstant.BUSINESS_KEY, businessKey);
        variables.put(WorkflowConstant.USER_ID, userId);


        ProcessInstance processInstance = processEngine.getRuntimeService().startProcessInstanceByKey(processKey, businessKey, variables);
        log.info("----------------------start proccess success!procInstanceId={}", processInstance.getId());

        return processInstance;
    }


    /**
     * 提交任务节点
     *
     * @param taskId    任务ID
     * @param variables 变量
     * @param userId    当前用户ID
     */
    public void completeTask(String taskId, Map<String, Object> variables, String userId) {
        if (null == variables) {
            variables = new HashMap<>();
        }
        processEngine.getTaskService().complete(taskId, variables);

        System.out.println();
    }


}
